<template>
  <svg class="trend-chart" width="60" height="24" :aria-label="trendDescription">
    <polyline
      :points="computedPoints"
      :stroke="trendColor"
      fill="none"
      stroke-width="2"
      stroke-linecap="round"
      stroke-linejoin="round"
      :class="{ 'trend-up': isUpTrend, 'trend-down': isDownTrend }"
    />
  </svg>
</template>

<script>
export default {
  name: 'TrendLine',
  props: {
    /**
     * 价格数据数组，包含7天的价格点
     */
    data: {
      type: Array,
      required: true,
      default: () => []
    }
  },
  computed: {
    /**
     * 计算SVG路径的点坐标
     * 将价格数据映射到SVG视图的坐标系统
     */
    computedPoints() {
      if (this.data.length < 2) return ''
      
      // 计算价格范围
      const minVal = Math.min(...this.data)
      const maxVal = Math.max(...this.data)
      const range = maxVal - minVal || 1 // 避免除以0
      
      // 计算每个点的坐标
      return this.data.map((value, index) => {
        // X坐标：平均分布在60px宽度内
        const x = index * (58 / (this.data.length - 1)) + 1
        // Y坐标：将价格值映射到24px高度内（底部为0，顶部为24）
        const y = 23 - ((value - minVal) / range) * 22
        return `${x.toFixed(1)},${y.toFixed(1)}`
      }).join(' ')
    },
    
    /**
     * 确定趋势颜色
     * 上涨趋势为绿色，下跌趋势为红色，持平为灰色
     */
    trendColor() {
      if (this.data.length < 2) return '#94a3b8'
      
      const firstValue = this.data[0]
      const lastValue = this.data[this.data.length - 1]
      
      if (lastValue > firstValue) return '#10b981' // 上涨 - 绿色
      if (lastValue < firstValue) return '#ef4444' // 下跌 - 红色
      return '#94a3b8' // 持平 - 灰色
    },
    
    /**
     * 判断是否为上涨趋势
     */
    isUpTrend() {
      if (this.data.length < 2) return false
      return this.data[this.data.length - 1] > this.data[0]
    },
    
    /**
     * 判断是否为下跌趋势
     */
    isDownTrend() {
      if (this.data.length < 2) return false
      return this.data[this.data.length - 1] < this.data[0]
    },
    
    /**
     * 生成无障碍描述文本
     */
    trendDescription() {
      if (this.data.length < 2) return '价格趋势数据不足'
      
      const changePercent = ((this.data[this.data.length - 1] - this.data[0]) / this.data[0] * 100).toFixed(2)
      return `7天价格${this.isUpTrend ? '上涨' : this.isDownTrend ? '下跌' : '持平'}${changePercent}%`
    }
  }
}
</script>

<style scoped>
.trend-chart {
  display: inline-block;
  vertical-align: middle;
  transition: all 0.3s ease;
}

/* 可以添加动画效果增强视觉体验 */
.trend-up polyline {
  animation: trendUp 1s ease-out;
}

.trend-down polyline {
  animation: trendDown 1s ease-out;
}

@keyframes trendUp {
  0% {
    stroke-dasharray: 1000;
    stroke-dashoffset: 1000;
  }
  100% {
    stroke-dasharray: 1000;
    stroke-dashoffset: 0;
  }
}

@keyframes trendDown {
  0% {
    stroke-dasharray: 1000;
    stroke-dashoffset: 1000;
  }
  100% {
    stroke-dasharray: 1000;
    stroke-dashoffset: 0;
  }
}
</style>
    